<template>
  <!-- 生成合同1页面-关联页面 -->
  <div class="generate-contract">
    <div class="form">
      <a-skeleton v-if="skeletonVisible" />
      <c-form
        v-else
        v-model="form"
        :col="{ labelCol: { span: 2 }, wrapperCol: {} }"
        ref="form"
        :data="formData"
        :rules="formRules"
        @submit="submit"
        :submitLoading="submitLoading"
      >
        <template v-slot:contractType>
          <a-input
            :placeholder="identity == '1' ? '采购' : '销售'"
            disabled
          ></a-input>
        </template>
        <template v-slot:categoryId>
          <a-select
            v-if="$route.query.orderId"
            :disabled="$route.query.orderId ? true : false"
            v-model="categoryName"
          ></a-select>
          <c-category
            v-else
            :disabled="$route.query.orderId ? true : false"
            class="select-input"
            v-model="form.categoryId"
            @change="categoryChange"
          ></c-category>
        </template>
        <template v-slot:order>
          <div class="table-wwrap">
            <a-table
              size="small"
              :loading="orderTableLoading"
              :row-selection="rowSelection"
              :columns="columns"
              :pagination="false"
              :data-source="pageData"
              rowKey="orderId"
            >
              <template slot="midpointsPeople" slot-scope="row">
                <span> {{ row.customerUser.realName }}</span>
              </template>
              <template slot="phone" slot-scope="row">
                <span> {{ row.customerUser.phone }}</span>
              </template>
              <div slot="categoryName" slot-scope="row">
                <span>{{ row.categoryName }}</span>
                <a-divider type="vertical" />
                <span>{{ row.brand }} </span>
                <span>{{ row.spec }} </span>
                <span>{{ row.material }} </span>
                <span>{{ row.other }} </span>
              </div>
              <template slot="createDate" slot-scope="row">
                <span>{{ $getTime(row.createDate) }}</span>
              </template>
            </a-table>
            <!-- <p class="tr">
              共
              <span class="primary">1</span>
              个订单，已选择了
              <span class="primary">1</span>
              个订单
            </p> -->
          </div>
        </template>
        <template v-slot:deliveryDate>
          <a-date-picker
            :disabled-date="disabledDate"
            v-model="form.deliveryDate"
            @change="onDeliveryDateChange"
          />
        </template>
        <template v-slot:currentCompany>
          <a-space>
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{ form.currentCompany }}</span>
              </template>
              <span>
                <a-input :placeholder="form.currentCompany" disabled
              /></span>
            </a-tooltip>

            <a-button class="fs-12" @click="replaceHead"
              >更换抬头</a-button
            ></a-space
          >
        </template>
        <template v-slot:dealCompanyId>
          <a-select
            :disabled="$route.query.orderId ? true : false"
            allowClear
            v-model="form.dealCompanyId"
            :placeholder="'请选择交易公司'"
            @change="dealCompanySelect"
          >
            <a-select-option
              v-for="(item, idx) in dealCompanyList"
              :value="item.id"
              :key="idx"
            >
              {{ item.companyName }}
            </a-select-option>
          </a-select>
        </template>
        <template v-slot:signDate>
          <a-date-picker
            v-model="form.signDate"
            :disabled-date="disabledDate"
            @change="onSignDateChange"
          />
        </template>
      </c-form>
    </div>
    <a-modal
      v-model="confirmVisible"
      title="请选择更换的抬头"
      width="560px"
      footer=""
    >
      <a-table
        size="small"
        :columns="moduleColumns"
        :loading="companyHeadTableLoading"
        :data-source="companyHeadData"
        :pagination="false"
        rowKey="companyId"
      >
        <div slot="handle" slot-scope="row">
          <span v-if="row.companyId == currentCompanyId">当前使用</span>
          <span
            v-else
            class="primary cursor-pointer"
            @click="confirmReplaceHead(row)"
            >更换为此抬头
          </span>
        </div>
      </a-table>
      <p class="add-head">
        <span>找不到抬头？</span
        ><span class="primary cursor-pointer" @click="addHead">新增抬头</span>
      </p>
      <span class="fs-12"
        ><a-icon
          class="icon"
          type="info-circle"
        />可更换的抬头均是当前账户已认证通过的公司抬头，未认证通过的不可更换。</span
      >
    </a-modal>
  </div>
</template>
<script>
import moment from "moment";
import { getCurIdentity } from "@/util/common";
import {
  getSellerAssociatedOrderList,
  getBuyerAssociatedOrderList,
  getBuyerCustomerCompanyList,
  getSellerCustomerCompanyList,
  getContractTemplate,
  getBuyerContractSelectCompanyList,
  getSellerContractSelectCompanyList
} from "@/api/contract/associatedOrder";
import { getOrderDetail } from "@/api/order";

const formRules = {
  dealCompanyId: [
    { required: true, message: "请选择交易公司", trigger: "change" }
  ],
  categoryId: [
    { required: true, message: "请输入商品种类", trigger: "change" }
  ],
  contractTemplateId: [
    { required: true, message: "请输入合同模板", trigger: "change" }
  ],
  contractCode: [
    { required: true, message: "请输入自定义编号", trigger: "change" }
  ],
  signDate: [{ required: true, message: "请输入签订日期", trigger: "change" }],
  deliveryPlace: [
    { required: true, message: "请输入指定地址", trigger: "change" }
  ]
};
const columns = [
  {
    title: "商品品名",
    key: "categoryName",
    scopedSlots: { customRender: "categoryName" }
  },
  {
    title: "仓库简称",
    dataIndex: "warehouseShortName",
    key: "warehouseShortName"
  },
  {
    title: "成交数（吨）",
    key: "dealAmount",
    dataIndex: "dealAmount"
  },
  {
    title: "基价（元）",
    key: "basePrice",
    dataIndex: "basePrice"
  },
  {
    title: "合约月",
    key: "futuresContract",
    dataIndex: "futuresContract"
  },
  {
    title: "点价人",
    key: "midpointsPeople",
    scopedSlots: { customRender: "midpointsPeople" }
  },
  {
    title: "手机号",
    key: "phone",
    scopedSlots: { customRender: "phone" }
  },
  {
    title: "升贴水（元）",
    key: "premium",
    dataIndex: "premium"
  },
  {
    title: "日期",
    key: "createDate",
    scopedSlots: { customRender: "createDate" }
  }
];

const moduleColumns = [
  {
    title: "公司全称",
    dataIndex: "companyName",
    key: "companyName"
  },
  {
    title: "操作",
    key: "handle",
    scopedSlots: { customRender: "handle" }
  }
];
export default {
  name: "AssociatedOrder",
  components: {},
  data() {
    return {
      category: [],
      currentCompanyId: "", //当前抬头ID
      current: 0,
      companyHeadTableLoading: false, //新增抬头table的loading
      orderTableLoading: false, //关联订单table的loading
      confirmVisible: false,
      skeletonVisible: false,
      submitLoading: false,
      pageData: [], //页面数据列表
      dealCompanyList: [], //交易公司列表
      contractTemplateList: [], //合同模板列表
      companyHeadData: [], //更换抬头列表
      beforeChangeCompanyId: "", //更换抬头前ID
      categoryName: "",
      targetCompanyName: "",
      form: {
        contractTemplateId: undefined,
        dealCompanyId: undefined,
        currentCompany: "",
        evaluateWay: 1,
        priceType: 1,
        categoryId: [],
        deliveryPlaceType: 1,
        contractCodeType: 1,
        deliveryDate: moment(new Date(), "YYYY-MM-DD"),
        signDate: moment(new Date(), "YYYY-MM-DD")
      },
      orederSelectedRowList: [],
      selectedRowKeys: [],
      formRules,
      columns,
      moduleColumns
    };
  },
  computed: {
    rowSelection() {
      const { selectedRowKeys } = this;
      return {
        selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
          this.orederSelectedRowList = selectedRows;
        }
      };
    },
    identity() {
      return getCurIdentity(); //1买家，2卖家
    },
    formData() {
      let res = [
        {
          label: "合同类型",
          prop: "contractType",
          disabled: true,
          slot: "contractType"
        },
        {
          label: "当前抬头",
          prop: "currentCompany",
          slot: "currentCompany"
        },
        {
          label: "交易公司",
          prop: "dealCompanyId",
          type: "select",
          slot: "dealCompanyId"
        },
        {
          label: "商品种类",
          prop: "categoryId",
          type: "select",
          slot: "categoryId"
        },
        {
          label: "合同模板",
          prop: "contractTemplateId",
          type: "select",
          showSearch: "false",
          typeData: this.contractTemplateList
        },
        {
          label: "作价方式",
          prop: "priceType",
          type: "select",
          typeData: [
            {
              label: "点价",
              value: 1
            },
            {
              label: "确定价",
              value: 2
            }
            // {
            //   label: "延期点价",
            //   value: 3
            // }
          ],
          disabled: this.$route.query.orderId ? true : false
        },
        {
          label: "关联订单",
          prop: "order",
          slot: "order"
        },
        {
          label: "交货地点",
          prop: "deliveryPlaceType",
          type: "select",
          typeData: [
            {
              label: "根据订单仓库全称",
              value: 1
            },
            {
              label: "指定地址",
              value: 2
            }
          ]
        },
        {
          label: "指定地址",
          prop: "deliveryPlace",
          hidden: this.form.deliveryPlaceType === 2 ? false : true
        },
        {
          label: "交货日期",
          prop: "deliveryDate",
          slot: "deliveryDate"
        },
        {
          label: "合同编号",
          prop: "contractCodeType",
          type: "select",
          typeData: [
            {
              label: "系统自动生成",
              value: 1
            },
            {
              label: "自定义",
              value: 2
            },
            {
              label: "留空不填",
              value: 3
            }
          ]
        },
        {
          label: "自定义编号",
          prop: "contractCode",
          hidden: this.form.contractCodeType === 2 ? false : true
        },
        {
          label: "签订地",
          prop: "signPlace"
        },
        {
          label: "签订日期",
          prop: "signDate",
          slot: "signDate"
        },
        {
          label: " ",
          colon: false,
          type: "submit",
          submitText: "下一步"
        }
      ];
      return res;
    }
  },

  created() {
    this.getTradingCompany();
    this.getCompanyInfo();
    if (this.$route.query.orderId) {
      this.getOrderDetail();
    }
  },
  methods: {
    moment,
    //更换抬头
    confirmReplaceHead(row) {
      let self = this;
      this.currentCompanyId = row.companyId;
      this.form.currentCompany = row.companyName;
      this.$message.success("切换成功");
      setTimeout(function() {
        self.confirmVisible = false;
      }, 1000);
    },
    //获取切换公司列表
    getSelectCompanyList() {
      this.companyHeadTableLoading = true;
      let identity = this.identity;
      let requestFun =
        identity == 1
          ? getBuyerContractSelectCompanyList
          : getSellerContractSelectCompanyList;
      requestFun({}).then(res => {
        this.companyHeadData = res;
        this.companyHeadTableLoading = false;
      });
    },
    //获取合同模板
    getTemplate() {
      getContractTemplate({
        categoryId: this.form.categoryId[this.form.categoryId.length - 1],
        currentCompanyId: this.currentCompanyId,
        beforeChangeCompanyId: this.beforeChangeCompanyId,
        dealCompanyId: this.form.dealCompanyId
      }).then(res => {
        // console.log(res)
        if (res && res.length > 0) {
          this.form.contractTemplateId = res[0].id;
          this.contractTemplateList = res.map(item => ({
            value: item.id,
            label: item.templateName
          }));
        }
      });
    },
    //获取交易公司
    getTradingCompany() {
      this.skeletonVisible = true;
      let identity = this.identity;
      let requestFun;
      identity == 1
        ? (requestFun = getBuyerCustomerCompanyList)
        : (requestFun = getSellerCustomerCompanyList);
      requestFun({}).then(res => {
        this.dealCompanyList = res;
        this.skeletonVisible = false;
      });
    },
    // 选择商品品种
    categoryChange(val) {
      this.form.categoryId = val;
      if (this.form.dealCompanyId) {
        this.getAssociatedOrderList();
        this.getTemplate();
      }
    },
    // 选择交易公司
    dealCompanySelect(val) {
      this.form.dealCompanyId = val;
      if (this.form.categoryId.length != 0) {
        this.getAssociatedOrderList();
        this.getTemplate();
      }
    },
    // 查询订单详情
    getOrderDetail() {
      let identity = this.identity;
      getOrderDetail({
        orderId: this.$route.query.orderId
      }).then(res => {
        this.form.priceType = res.priceType;
        this.form.dealCompanyId =
          identity == 1 ? res.providerCompany.id : res.customerCompany.id;
        this.targetCompanyName =
          identity == 1
            ? res.providerCompany.companyName
            : res.customerCompany.companyName;
        this.categoryName = res.categoryName;
        this.form.categoryId = ["", res.categoryId];
        if (res.categoryId) {
          this.getAssociatedOrderList();
        }
        //获取合同模板
        this.getTemplate();
      });
    },
    //获取当前抬头信息
    getCompanyInfo() {
      let companyInfo = this.$storage.get("companyInfo");
      this.currentCompanyId = companyInfo.id;
      this.form.currentCompany = companyInfo.companyName;
      //更换前的抬头
      this.beforeChangeCompanyId = companyInfo.id;
    },
    disabledDate(current) {
      return current && current < moment().subtract(1, "days");
    },
    onDeliveryDateChange(date) {
      this.form.deliveryDate = date;
    },
    onSignDateChange(date) {
      this.form.signDate = date;
    },
    //新增抬头
    addHead() {
      this.$storage.s_set("addCompany", true);
      this.$router.push({ name: "authentication" });
    },
    // 更换抬头
    replaceHead() {
      this.getSelectCompanyList();
      this.confirmVisible = true;
    },
    submit() {
      if (this.orederSelectedRowList.length === 0) {
        this.$message.warning("请选择关联的订单");
        return;
      }
      let parmas = {
        priceType: this.form.priceType,
        currentCompanyId: this.currentCompanyId,
        dealCompanyId: this.form.dealCompanyId,
        contractCodeType: this.form.contractCodeType,
        contractCode: this.form.contractCode,
        signPlace: this.form.signPlace,
        signDate: moment(this.form.signDate).format("YYYY-MM-DD"),
        deliveryDate: moment(this.form.deliveryDate).format("YYYY-MM-DD"),
        deliveryPlace: this.form.deliveryPlace,
        categoryId: this.form.categoryId[this.form.categoryId.length - 1],
        contractTemplateId: this.form.contractTemplateId,
        deliveryPlaceType: this.form.deliveryPlaceType,
        beforeChangeCompanyId: this.beforeChangeCompanyId
      };
      //存储创建订单数据

      this.$storage.s_set("createContractparams", parmas);
      //存储关联合同订单数据
      this.$storage.s_set("createContractOrder", this.orederSelectedRowList);
      this.$emit("onStepChange", 1);
    },
    //获取可关联合同的订单
    getAssociatedOrderList() {
      this.orderTableLoading = true;
      let requesFun =
        this.identity == 1
          ? getBuyerAssociatedOrderList
          : getSellerAssociatedOrderList;
      requesFun({
        orderId: this.$route.query.orderId,
        targetCompanyId: this.form.dealCompanyId, //交易公司
        categoryId: this.form.categoryId[this.form.categoryId.length - 1], //类别ID
        priceType: this.form.priceType //作价方式:1点价 2确定价
      })
        .then(res => {
          this.pageData = res;
          if (res && res.length > 0) {
            res.forEach(item => {
              if (item.orderId == this.$route.query.orderId) {
                this.selectedRowKeys = [item.orderId]; //默认勾选订单/订单详情跳转过来的订单
                this.orederSelectedRowList = [item];
              }
            });
          }
          this.orderTableLoading = false;
        })
        .finally(() => {});
    },
    pageChange(pagination) {
      this.pageNum = pagination;
    }
  },
  beforeDestroy() {
    clearTimeout();
  }
};
</script>

<style lang="scss" scoped>
.generate-contract {
  .select-input {
    width: 220px;
    margin-right: 5px;
  }
  background: #fff;
  ::v-deep .ant-input {
    width: 220px;
  }
  .sumbit-btn {
    width: 100px;
  }
  ::v-deep .ant-btn-block {
    width: 100px;
  }
  ::v-deep .ant-select {
    width: 220px;
  }
  .step {
    padding: 50px;
  }
  .form {
    padding: 0 50px 30px 20px;
  }
  .table-wwrap {
    border: 1px solid #e8e8e8;
    p {
      margin: 0px 10px;
      font-size: 12px;
    }
  }
}
.icon {
  color: #e6a23c;
  margin-right: 2px;
}
.add-head {
  margin: 20px 0 0 0;
}
</style>
